#include "tailor.h"
#include "qdebug.h"
#include"global.h"

Tailor::Tailor(QObject *parent)
    : QObject{parent}
{

}

void Tailor::coordinates(const double &pictureW, const double &x, const double &y, const double &w, const double &h)
{
    // 将URL格式的路径转换为标准文件路径
    if (m_url.startsWith("file:///")) {
        m_url = m_url.mid(8);  // 移除前缀 "file:///"
    }
    if (m_url.startsWith("qrc:")) {
        m_url = m_url.mid(3);  // 移除前缀 "qrc:"
    }
    //QImage适合对图片的处理 QPixmap适合显示
    QImage image(m_url);
    if (image.isNull()){
        qDebug() << "Failed to load image.";
        return;
    }

    double scaling = image.width() / pictureW;
    QRect cropRect(x * scaling, y * scaling, w * scaling, h * scaling);
    QImage croppedPixmap = image.copy(cropRect);

    // 指定要保存的文件路径和名称
    QString filePath = TemporaryAvatar; // 可以是任意路径和文件名
    // 保存图片到文件
    bool success = croppedPixmap.save(filePath, "JPG"); // 可以选择其他格式如"PNG"
    if (!success) {
        qDebug() << "Failed to save image.";
    } else {
        qDebug() << "Image saved successfully.";
    }

    emit sig_head_portrait_finish();
}

Tailor::~Tailor()
{
    qDebug("Tailor::~Tailor");
}

QString Tailor::url() const
{
    return m_url;
}

void Tailor::setUrl(const QString &newUrl)
{
    if (m_url == newUrl)
        return;
    m_url = newUrl;
    emit urlChanged();
}
